import { useUserInfo } from '@/store/userInfo'
import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
    {
        name: 'main',
        path: '/',
        redirect: '/chat'
    },
    {
        name: 'chat',
        path: '/chat',
        component: () => import('../views/chat/chat.vue')
    },
    {
        name: 'login',
        path: '/login',
        component: () => import('../views/login/login.vue')
    },
    {
        name: '404',
        path: '/404',
        component: () => import('../views/404/404.vue'),
    },
    {
        path: '/:pathMatch(.*)',
        redirect: '/404',
      }
    
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

router.beforeEach((to, from, next) => {
    if(useUserInfo().getterToken) {
        next()
    } else {
        if(to.path == '/login') {
            next()
        } else {
            next({
                replace: true,
                name: 'login'
            })
        }
    }
})

router.afterEach((to, from) => {
   document.title = to.name?.toString() || ''
});

export default router